<template>
  <div class="loginBox">
    <el-form
      :rules="rules"
      status-icon
      label-width="100px"
      class="demo-ruleForm"
      :model="users"
      ref="users"
    >
      <h2 style="text-align: center; margin-bottom: 20px">图书管理系统</h2>
      <el-form-item label="用户名" prop="username">
        <el-input
          type="text"
          autocomplete="off"
          v-model="users.username"
          style="width: 70%"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          autocomplete="off"
          v-model="users.password"
          style="width: 70%"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button style="width: 70%" type="primary" @click="submit"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from "@/api/";
export default {
  data() {
    return {
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      users: {
        username: "",
        password: "",
      },
    };
  },
  methods: {
    submit() {
      this.$refs.users.validate(async (valid) => {
        if (valid) {
          const { data } = await login({
            username: this.users.username,
            password: this.users.password,
          });
          //   console.log(data);
          let { code, message, token, refreshToken } = data;
          if (code === 20000) {
            this.$message({
              message,
              type: "success",
            });
            // sessionStorage.setItem("token", token);
            this.$store.commit("addToken", token);
            this.$store.commit("addRefreshToken", refreshToken);
            this.$store.commit("addUser", this.users.username);
            this.$router.push("/index");
          } else {
            this.$message.error(message);
          }
          this.users.username = "";
          this.users.password = "";
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.loginBox {
  height: 662px;
  background: transparent
    url("https://img-baofun.zhhainiao.com/fs/6001aafbf353664023c36347b5372e10.jpg")
    repeat-y fixed top;
  background-size: cover;
}
.el-form {
  width: 500px;
  height: 662px;
  border: 1px solid #ccc;
  position: absolute;
  right: 0;
  padding-top: 100px;
  background-color: rgba(255, 255, 255, 0.7);
}
</style>